package com.abbas.smartCity.ui;

import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.abbas.smartCity.App;
import com.abbas.smartCity.R;
import com.abbas.smartCity.base.BaseActivity;
import com.abbas.smartCity.bean.LoginBean;
import com.abbas.smartCity.bean.NetBean;
import com.abbas.smartCity.bean.ServerDTO;
import com.abbas.smartCity.bean.UserInfoBean;
import com.abbas.smartCity.retroft.ICallback;
import com.abbas.smartCity.retroft.ICallback2;
import com.abbas.smartCity.util.DialogManager;

import java.util.Map;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 登录页面实现
 */
public class LoginActivity extends BaseActivity {

    private EditText accEt;
    private EditText passEt;
    private Button loginBt;

//    private Handler handler = new Handler();

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView();

//        //TODO OkHttp 使用
//        // Step 1 创建OkHttpClient /////GET
//        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .build();
//        // Step 2 创建Request对象并指定访问地址
//        final Request request = new Request.Builder()
//                .url(baseUrl + "/prod-api/api/login")
//                .build();
//        // Step 3 发送请求
//        new Thread(() -> {
//            try {
//                final Response response = okHttpClient.newCall(request).execute();
//                Log.e("response",response.toString());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }).start();
//
//        //POST
//        //Step 2 构建请求体
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),"哈哈");
//
//        //Step 3
//        final Request postRequest = new Request.Builder()
//                .url(baseUrl + "/prod-api/api/login")
//                .post(requestBody)
//                .build();

    //Step 4 发送请求
//        new Thread(() -> {
//            try {
//                final Response postResponse = okHttpClient.newCall(postRequest).execute();
//                Log.e("postResponse",postResponse.toString());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }).start();

    //异步请求 不用线程
//        okHttpClient.newCall(postRequest).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                int a = 1+1;
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                int a = 1+1;
////                handler.post(() -> Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show());
//                runOnUiThread(() -> Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show());
//            }
//        });

    //TODO Retrofit 使用
    //Step 1 创建一个接口

    //Step 2 创建Retrofit 对象

    //Gson使用
    //将字符串解析成为对象
//        final TestClass testClass = new Gson().fromJson("{\n" +
//                "\"username\":\"test01\",\n" +
//                "\"password\":\"123456\"\n" +
//                "}", TestClass.class);
//
//        //将对象解析成为字符串
//        final String s = new Gson().toJson(testClass);
//    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected boolean enableUp() {
        return false;
    }

    @Override
    protected String setCustomTitle() {
        return "登录";
    }

    @Override
    protected void initView() {
        accEt = (EditText) findViewById(R.id.acc_et);
        passEt = (EditText) findViewById(R.id.pass_et);
        loginBt = (Button) findViewById(R.id.login_bt);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        //登录按钮的点击事件
        loginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Map<String, Object> params = getMap();
                params.put("username", accEt.getText().toString());
                params.put("password", passEt.getText().toString());
                api.login(
                        createRequestBody(params)
                ).enqueue(new ICallback<LoginBean>() {
                    @Override
                    public void onSuccess(Call<LoginBean> call, LoginBean data) {
                        //存储token
                        App.getSharedPreferences()
                                .edit()
                                .putString("token", data.getToken())
                                .apply();
                        api.getUserInfo().enqueue(new ICallback<UserInfoBean>() {
                            @Override
                            public void onSuccess(Call<UserInfoBean> call, UserInfoBean data) {
                                //存储用户
                                App.setUser(data.getUser());

                                Toast.makeText(LoginActivity.this, "获取用户信息成功", Toast.LENGTH_SHORT).show();
                                //跳转到主页
                                startActivity(HomeActivity.class);
                                //登录
                                LoginActivity.this.finish();
                            }
                        });
                    }
                });
            }
        });
//        loginBt.setOnClickListener((v) -> {
//            //构造数据
//            final Map<String, Object> params = getMap();
//            params.put("username", accEt.getText().toString());
//            params.put("password", passEt.getText().toString());
//            //将数据转换成为json后放进请求体当中
//            final RequestBody requestBody1 = createRequestBody(params);
//
//            //显示等待弹窗(无聊做着玩的哈，不用管这个弹窗
//            int max = 2;
//            int now = 0;
//            int future = 1;
//            LiveData<Integer> nowLiveData = new LiveData<>(now);
//            LiveData<Integer> futureData = new LiveData<>(future);
//            final ProgressDialog dialog = DialogManager.getInstance().getDialog(max, nowLiveData, futureData);
//            dialog.show();
//            dialog.setMessage("请求用户令牌");
//            //Step 3 开始请求
//            api.login(requestBody1).enqueue(new ICallback<LoginBean>() {
//                @Override
//                public void onSuccess(Call<LoginBean> call, LoginBean loginBean) {
//                    //设置弹窗进度
//                    nowLiveData.setData(1);
//                    futureData.setData(2);
//
//                    //存储token
//                    App.getSharedPreferences()
//                            .edit()
//                            .putString("token", loginBean.getToken())
//                            .apply();
//
//                    Log.e("retrofit2", loginBean.toString());
//                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
//
//                    //获取到token之后直接拿用户信息先存起来
//                    dialog.setMessage("获取用户数据");
//                    api.getUserInfo().enqueue(new ICallback<UserInfoBean>() {
//                        @Override
//                        public void onSuccess(Call<UserInfoBean> call, UserInfoBean data) {
//                            //修改进度
//                            nowLiveData.setData(2);
//                            //存储用户
//                            App.setUser(data.getUser());
//                            //弹窗取消
//                            dialog.dismiss();
//                            Toast.makeText(LoginActivity.this, "获取用户信息成功", Toast.LENGTH_SHORT).show();
//                            //跳转到主页
//                            startActivity(HomeActivity.class);
//                            //登录
//                            LoginActivity.this.finish();
//                        }
//
//                        @Override
//                        public void onActFailure(Call<UserInfoBean> call, Throwable throwable, Response<UserInfoBean> response) {
//                            super.onActFailure(call, throwable, response);
//                            dialog.dismiss();
//                        }
//                    });
//
//                }
//
//                @Override
//                public void onActFailure(Call<LoginBean> call, Throwable throwable, Response<LoginBean> response) {
//                    super.onActFailure(call, throwable, response);
//                    dialog.dismiss();
//                }
//            });
//        });
    }

}